//
//  NetWrokTools.swift
//  weibo
//
//  Created by cmh on 15/9/2.
//  Copyright © 2015年 cmh. All rights reserved.
//

import UIKit
import AFNetworking
import ReactiveCocoa

enum RequestMethod: String{
    case GET = "GET"
    case POST = "POST"
}

class NetWrokTools: AFHTTPSessionManager {
    
    private let client_id = "1418233852"
    
    private let appSecret = "8bce9762a5c5005411e63439c3830daf"
    
    let redirect_uri = "http://www.baidu.com"
    
    // 单例
    static let shareTools: NetWrokTools = {
    
        var instance = NetWrokTools(baseURL: nil)
        
        // 设置反序列化的支出格式
        instance.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        return instance
    
    }()
    
    // MARK: OAuth
    /// OAuth 授权url
    /// - see: [https://api.weibo.com/oauth2/authorize](https://api.weibo.com/oauth2/authorize)
    var oauthUrl: NSURL {
    
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(client_id)&redirect_uri=\(redirect_uri)"
        
        return NSURL(string: urlString)!

    }
    
    /// 获取AccessToken
    /// - see: [https://api.weibo.com/oauth2/access_token](https://api.weibo.com/oauth2/access_token)
    func loadAccessToken(code: String) -> RACSignal {
    
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        let params = ["client_id" : client_id, "client_secret" : appSecret, "grant_type" : "authorization_code", "code" : code,  "redirect_uri" : redirect_uri]
        
        return  request(.POST, URLString: urlString, parameters: params, needToken: false)
        
    }
    
    // 加载用户信息
    /// - see: [https://api.weibo.com/2/users/show.json](https://api.weibo.com/2/users/show.json)
    func loadUserInfo(uid: String) -> RACSignal {
        let urlString = "https://api.weibo.com/2/users/show.json"
        
        let params = ["uid": uid]
        
        return request(.GET, URLString: urlString, parameters: params)
    }
    
    // 加载微博数据
    func loadStatus(since_id since_id: Int, max_id: Int) -> RACSignal {
        
        let ursString = "https://api.weibo.com/2/statuses/home_timeline.json"
        
        var params = [String: AnyObject]()
        
        if since_id > 0 {
            params["since_id"] = since_id
        } else if max_id > 0 {
            params["max_id"] = max_id - 1
        }
        
        return request(.GET, URLString: ursString, parameters: params)
        
    
    }
    
    /// 网络请求方法
    func request(menthod: RequestMethod, URLString: String, var parameters: [String: AnyObject]?, needToken: Bool = true) -> RACSignal {
    
        return RACSignal.createSignal({ (subscriber) -> RACDisposable! in
            
            // 判断是否需要token
            if needToken {
            
                // 判断token是否有值,没有值会调用
                guard let token = UserAccountViewModel.shareUserAccount.accessToken else {
                
                    // 发送token为空的消息
                    subscriber.sendError(NSError(domain: "com.itheima.error", code: 1000, userInfo: ["errorMessage": "Token 为空"]))
                    return nil
                    
                }
                
                // 判断是否传了参数字典,实例化
                if parameters == nil {
                    parameters = [String: AnyObject]()
                }
                
                // 这是token都是有值的
                parameters!["access_token"] = token
            }
            
            
            // 成功的回调闭包
            let successBlack = { (task: NSURLSessionDataTask, result: AnyObject) -> Void in
                
                // 将结果发送给订阅者
                subscriber.sendNext(result)
            
                // 完成
                subscriber.sendCompleted()
            }
            
            // 失败的回调闭包
            let errorBlack = { (task: NSURLSessionDataTask, error: NSError) -> Void in
                
                // 将失败的结果发送给订阅者
                subscriber.sendError(error)
            }
            
            // 根据方法，调用不同的网络方法
            if menthod == .GET {
                self.GET(URLString, parameters: parameters, success: successBlack, failure: errorBlack)
            } else{
                self.POST(URLString, parameters: parameters, success: successBlack, failure: errorBlack)
            }
            
            
            return nil
        })
        
    }
    
}
